package com.kdg.thread;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author kdg
 * @description:  让普通变量也享受原子操作
 * @date 2018/5/11.
 */
public class AtomicIntegerFiledUpdaterTest {
    public static class Candidate{
        int id;
        volatile int score;
    }

    /**
     * 该无锁类使用时变量 Must be volatile type
     */
    static AtomicIntegerFieldUpdater<Candidate> socreCandidate = AtomicIntegerFieldUpdater.newUpdater(Candidate.class,"score");
    static AtomicInteger allSocre = new AtomicInteger(0);
    static Integer allScoreCommon = 0;

    public static void main(String[] args) throws InterruptedException {
        Candidate candidate = new Candidate();
        Thread[] threads = new Thread[10000];
        for(int i=0;i<10000;i++){
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    if(Math.random() > 0.4){
                        allScoreCommon += 1;
                        allSocre.incrementAndGet();
                        socreCandidate.incrementAndGet(candidate);
                    }
                }
            });
            threads[i].start();
        }
        for(int i=0;i<10000;i++){
            threads[i].join();
        }
        System.out.println("allScore is "+ allSocre.get());
        System.out.println("score is " + candidate.score);
        System.out.println("allScoreCommon is "+ allScoreCommon);
    }

}
